package com.javabasic.algorithm.leetcode;

public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = null, point = null;
        int temp = 0;
        boolean flag = true;
        while (l1 != null || l2 != null) {
            if (l1 != null && l2 != null) {
                temp = l1.val + l2.val + temp;
                l1 = l1.next;
                l2 = l2.next;
            } else if (l1 != null && l2 == null) {
                temp = l1.val + temp;
                l1 = l1.next;
            } else if (l1 == null && l2 != null) {
                temp = l2.val + temp;
                l2 = l2.next;
            }
            if (flag) {
                point = new ListNode(temp%10);
                result = point;
                flag = false;
            } else {
                point.next = new ListNode(temp%10);
                point = point.next;
            }
            temp /= 10;
        }
        while (temp > 0) {
            point.next = new ListNode(temp%10);
            point = point.next;
            temp /= 10;
        }
        return result;
    }

    // 空间优化
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode result = l1, pre = l1;
        int temp = 0;
        boolean flag = true;
        while (l1 != null || l2 != null) {
            if (l1 != null && l2 != null) {
                temp = l1.val + l2.val + temp;
                l1.val = temp%10;
                pre = l1;
                l1 = l1.next;
                l2 = l2.next;
            } else if (l1 != null && l2 == null) {
                temp = l1.val + temp;
                pre = l1;
                l1.val = temp%10;
                l1 = l1.next;
            } else if (l1 == null && l2 != null) {
                temp = l2.val + temp;
                pre.next = new ListNode(temp%10);
                pre = pre.next;
                l2 = l2.next;
            }
            temp /= 10;
        }
        while (temp > 0) {
            pre.next = new ListNode(temp%10);
            pre = pre.next;
            temp /= 10;
        }
        return result;
    }
}
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}